package com.ssyt.jfinal.core.article;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ssyt.jfinal.core.common.model.Article;
import com.ssyt.jfinal.core.common.utils.PageConstants;

public class ArticleService {

    @Before(Tx.class)
    public void delete(Integer id) {
        Article.dao.deleteById(id);
    }
    @Before(Tx.class)
	public void update(Article article) {
    	Record articleRecord = Db.findById("article", article.getId())
    			.set("title", article.getTitle())
				.set("content", article.getContent())
				.set("create_time", article.getCreateTime())
				.set("read_times", article.getReadTimes());
    	Db.update("article", articleRecord);
	}
    @Before(Tx.class)
	public Page<Record> list(Integer pageNo, String title) {
		String selectSql = "SELECT a.id, a.title, a.content, a.create_time AS createTime, a.read_times AS readTimes, u.code ";
    	StringBuilder fromSql = new StringBuilder("FROM article a, user u WHERE a.user_id = u.id ");
    	if(title != null) {
    		fromSql.append("AND a.title LIKE '%" + title + "%'");
    	}
    	
    	return Db.paginate(pageNo, PageConstants.PAGE_SIZE, selectSql, fromSql.toString());
	}
    @Before(Tx.class)
	public void add(Article article) {
		Record record = new Record()
				.set("title", article.getTitle())
				.set("content", article.getContent())
				.set("create_time", article.getCreateTime())
				.set("read_times", article.getReadTimes())
				.set("category_id", 1)
				.set("user_id", 1);
		Db.save("article", record);
	}
}
